import type { PlatformTypeValue, ThemeType } from '../../types/interfaces'
import type { StyleOperateType } from '../../user_center/tab/personalization/page_theme/types'
import type { PageType } from '../page_handler/type'
import { ConfigManager } from '../../module/config_manager'
import { AppModule } from '../../module/config_manager/types'
import { USER_ANALYTICS_MAX_COMMENT_PAGES } from '../../module/page_enhancer/data_presentation/platform/greasy_fork/user_analytics/types'
import {
  AppStyleCollections,
  GM_STORAGE_KEYS,
  HOSTNAME,
  logger,
  SUPPORTED_PLATFORMS,
  ThemeSettingsManager,
} from '../../types/constants'
import { ElementManager } from '../element_manager'
import { PageHandler } from '../page_handler'
import { BingPageType } from '../page_handler/platform/bing/types'
import { GreasyForkPageType } from '../page_handler/platform/greasyfork/types'
import { SoPageType } from '../page_handler/platform/so/types'
import { SogouPageType } from '../page_handler/platform/sogou/types'
import { getCurrentPlatformPageTypes } from '../page_handler/type'
import { ToolKit } from '../utils/toolkit'
import { PageStorage } from './storage/page_storage'

export interface ILatestThemeMeta {
  enabled: boolean
  theme: ThemeType
  styleOperateType: StyleOperateType
  date: string
}

export class PageManager extends PageStorage {
  id: string = 'page_manager'
  protected name: string = 'PageManager'
  usePageTypeIsolation = true
  private static instance: PageManager
  private configManager: ConfigManager = ConfigManager.getInstance()

  /**
   * 获取单例实例
   */
  public static getInstance(): PageManager {
    if (!PageManager.instance) {
      PageManager.instance = new PageManager()
    }
    return PageManager.instance
  }

  /**
   * 获取生效的主题
   */
  getEffectTheme(): ThemeType {
    const pageType = PageHandler.detectCurrentPageType()

    // 获取当前主题设置
    const themeSettings: any = ThemeSettingsManager.get()

    // 安全访问嵌套属性
    const pageTheme = themeSettings?.[pageType]?.theme

    return this.configManager.getFeatureEnabled(AppModule.ThemeSync.id) && pageTheme
      ? pageTheme
      : ToolKit.browser.theme.getCurrentTheme()
  }

  /**
   * 获取所有页面主题
   * @param showEmpty 是否显示空主题
   */
  getAllPageTheme(showEmpty = false): { pageType: PageType, theme: ThemeType }[] {
    const pageTypes = getCurrentPlatformPageTypes()
    return pageTypes.map((pageType) => {
      return {
        pageType,
        theme: this.getCurrentPageTheme() as ThemeType,
      }
    }).filter(item => item.theme || showEmpty)
  }

  /**
   * 获取当前页面主题
   */
  getCurrentPageTheme(): string {
    return this.storageGet(GM_STORAGE_KEYS.pageTheme, '')
  }

  /**
   * 检查所有页面主题是否统一
   * @returns 如果所有主题相同则返回该值，否则返回null
   */
  hasUniformThemes(): ThemeType | null {
    const themes = this.getAllPageTheme()

    if (themes.length === 0) {
      return null
    }

    // 获取第一个主题作为基准
    const baseTheme = themes[0].theme

    // 检查所有主题是否相同
    const allSame = themes.every(({ theme }) => theme === baseTheme)

    return allSame ? baseTheme : null
  }

  /**
   * 记录最新主题元数据
   * @param theme 主题类型
   * @param styleOperateType 样式操作类型
   */
  recordLatestThemeMeta(theme: ThemeType, styleOperateType: StyleOperateType): void {
    const meta = {
      enabled: this.configManager.getFeatureEnabled(AppModule.ThemeInherit.id),
      theme,
      styleOperateType,
      date: new Date().toLocaleString(),
    } as ILatestThemeMeta

    this.storageSet(GM_STORAGE_KEYS.latestThemeMeta, meta)

    logger.important(`[${this.name}] 最新主题元数据记录完成`, meta)
  }

  /**
   * 获取当前主题样式
   */
  getCurrentThemeStyle(): string {
    return this.storageGet(GM_STORAGE_KEYS.pageStyle, '')
  }

  /**
   * 获取背景图片 URL
   */
  getBackgroundImageUrl(): string {
    return this.storage.get(GM_STORAGE_KEYS.backgroundImage, '')
  }

  /**
   * 获取搜索-展示列数（默认）
   */
  get defaultSearchResultColumns(): number {
    const config: Partial<Record<PlatformTypeValue, Partial<Record<string, { columns: number }>>>> = {
      [SUPPORTED_PLATFORMS.SO_GOU]: {
        [SogouPageType.Video]: {
          columns: 5,
        },
      },
      [SUPPORTED_PLATFORMS.SO]: {
        [SoPageType.Video]: {
          columns: 5,
        },
      },
      [SUPPORTED_PLATFORMS.BING]: {
        [BingPageType.Video]: {
          columns: 5,
        },
      },
    }

    return config[HOSTNAME]?.[PageHandler.getCurrentPageType()]?.columns || 1
  }

  /**
   * 获取搜索-展示列数（设置）
   */
  getSearchResultColumns(dynamic: boolean = false): number {
    const column = Number.parseInt(String(this.storageGet(GM_STORAGE_KEYS.searchResultColumns, this.defaultSearchResultColumns)))
    return dynamic ? Math.min(column, ElementManager.getInstance().calculateMaxColumns()) : column
  }

  /**
   * 获取搜索-搜索数量
   */
  getSearchResultNum(): number {
    return Number.parseInt(String(this.storageGet(GM_STORAGE_KEYS.searchResultNum, 10)))
  }

  /**
   * 检查当前是否设置了有效壁纸
   * - 同时验证背景图是否存在且非空
   * - 支持检查CSS变量和常规背景图
   */
  hasActiveWallpaper(): boolean {
    const $wallpaper = $(`body > #${AppStyleCollections.Wallpaper.CONTAINER}`)

    if (!$wallpaper.length)
      return false

    const bgImage = $wallpaper.css('background-image')

    return this.isValidBackground(bgImage)
  }

  /**
   * 检测有效背景图
   */
  isValidBackground(bgImage: string | undefined): boolean {
    if (!bgImage)
      return false

    // 快速排除已知无效值
    const invalidValues = ['none', 'initial', 'inherit', 'unset']
    if (invalidValues.includes(bgImage.toLowerCase()))
      return false

    // 标准化处理
    const normalized = bgImage.replace(/\s+/g, ' ').trim()
    if (normalized === '')
      return false

    // 精确匹配空URL
    const emptyUrlPatterns = [
      'url("")',
      'url(\'\')',
      'url()',
      'url(" ")',
      'url(\' \')',
      'url( )',
    ]
    if (emptyUrlPatterns.includes(normalized))
      return false

    // 检查透明/未定义
    return !(
      normalized.includes('undefined')
      || normalized.includes('transparent')
      || normalized.includes('#0000')
    )
  }

  /**
   * 获取热门网站配置
   */
  getPopularLink(): string {
    return this.storage.get(GM_STORAGE_KEYS.popularLink, '')
  }

  /**
   * 获取加载中短语
   */
  getLoadingPhrases(): string {
    return this.storage.get(GM_STORAGE_KEYS.loadingPhrases, '', {
      useDomainIsolation: false,
    })
  }

  /**
   * 获取加载页数
   */
  getPageNum(): number {
    let defaultPageNum = 0

    if (HOSTNAME === SUPPORTED_PLATFORMS.GREASY_FORK && PageHandler.getCurrentPageType() === GreasyForkPageType.USER_PROFILE)
      defaultPageNum = USER_ANALYTICS_MAX_COMMENT_PAGES

    return Number.parseInt(String(this.storageGet(GM_STORAGE_KEYS.pageNum, defaultPageNum)))
  }
}
